import React, { Component } from 'react';
import { getZuixinsongByType, getSongsType, addCollect } from '../../utils/api';
import { bus } from '../../utils/eventBus';
import '../../style/all.css';
import './Zuixinsong.css';

export default class Zuixinsong extends Component {
	state = {
		// 当前歌曲类型id
		currentTypeId: 0,
		// 歌曲类型数组
		types: [],
		// 歌曲数组
		songsList: [],
	}
	componentDidMount () {
		window.scroll(0, 0);
		this.getSongs();
	}
	// 获取歌曲和歌曲类型
	async getSongs () {
		const types = await getSongsType();
		this.setState({
			types: types.data,
			currentTypeId: types.data[0].musictypeid
		}, function () {
			this.getZuixinsongs(this.state.currentTypeId);
		})
	}
	async getZuixinsongs (typeId) {
		const songs = await getZuixinsongByType(typeId);
		this.setState({
			songsList: songs.data
		})
	}
	// 切换音乐类型
	async changeCType (typeId) {
		const songs = await getZuixinsongByType(typeId);
		this.setState({
			songsList: songs.data,
			currentTypeId: typeId
		})
	}
	// 添加收藏
	async addCollects (musicid,e) {
		e.stopPropagation();
		let userid = Number(window.sessionStorage.getItem('userid'));
		let addC = await addCollect(userid, 0, musicid);
		if (addC.status === 0) {
			window.alert(addC.message);
		} else {
			window.alert(addC.message);
		}
	}
	render () {
		let { currentTypeId, types, songsList } = this.state;
		return (
			<div className='song main'>
				<div className='song_tag'>
					<ul>
						{types.map((item) => (
							<li key={item.musictypeid} onClick={() => { this.changeCType(item.musictypeid) }} className={currentTypeId === item.musictypeid ? 'active' : 'red'}>{item.musictype_name}</li>
						))}
					</ul>
				</div>
				<div className='song_list'>
					<h2>
						<span>id</span>
						<span>音乐标题</span>
						<span>歌手</span>
						<span>收藏</span>
					</h2>
					<ul>
						{songsList.map((item, index) => (
							<li key={item.musicid} onClick={() => { bus.emit('syplay', { id: item.musicid }) }}>
								<span>{index + 1}</span>
								<span>{item.music_name}</span>
								<span>{item.singer_name}</span>
								<span className='red' onClick={(e) => { this.addCollects(item.musicid,e) }}>添加收藏</span>
							</li>
						))}
					</ul>
				</div>
			</div>
		)
	}
}
